package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.BookTag;
import com.bookstore.back.entity.BookTagRelation;
import com.bookstore.back.mapper.BookTagRelationMapper;
import com.bookstore.back.service.BookTagRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 图书标签关联服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Service
public class BookTagRelationServiceImpl extends ServiceImpl<BookTagRelationMapper, BookTagRelation> implements BookTagRelationService {

    @Override
    public List<BookTag> getTagsByBookId(Integer bookId) {
        return baseMapper.getTagsByBookId(bookId);
    }

    @Override
    public Map<Integer, List<BookTag>> getTagsByBookIds(List<Integer> bookIds) {
        if (bookIds == null || bookIds.isEmpty()) {
            return new HashMap<>();
        }

        // 使用循环查询的方式，虽然不是最优但是简单可靠
        Map<Integer, List<BookTag>> result = new HashMap<>();
        for (Integer bookId : bookIds) {
            List<BookTag> tags = getTagsByBookId(bookId);
            result.put(bookId, tags != null ? tags : new ArrayList<>());
        }

        return result;
    }

    @Override
    @Transactional
    public boolean updateBookTags(Integer bookId, List<Integer> tagIds) {
        // 先删除原有的关联
        deleteBookTags(bookId);
        
        // 如果没有新的标签，直接返回
        if (tagIds == null || tagIds.isEmpty()) {
            return true;
        }
        
        // 添加新的关联
        List<BookTagRelation> relations = new ArrayList<>();
        for (Integer tagId : tagIds) {
            BookTagRelation relation = new BookTagRelation();
            relation.setBookId(bookId);
            relation.setTagId(tagId);
            relations.add(relation);
        }
        
        return this.saveBatch(relations);
    }

    @Override
    public boolean deleteBookTags(Integer bookId) {
        QueryWrapper<BookTagRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id", bookId);
        return this.remove(queryWrapper);
    }

}
